﻿// @Description: 快钱VPOS-CNP网关接口范例
// @Copyright (c) 上海快钱信息服务有限公司
// @version 1.0
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace DataReceive
{
    /// <summary>
    /// 获取TR3回传数据，发送TR4数据方法及验签函数
    /// </summary>
    public class KQHelper
    {
        private static object lockobj = new object();
        public static string mg = ""; //定义公共消息变量

        #region 公共接口
        /// <summary>
        /// TR4发送数据
        /// </summary>
        public void SendTR4(string reqXml)
        {
            lock (lockobj)
            {
                try
                {
                    //将TR4数据response到MAS
                    byte[] bytes = Encoding.GetEncoding("UTF-8").GetBytes(reqXml);
                    HttpResponse hr = HttpContext.Current.Response;
                    hr.Clear();
                    hr.OutputStream.Write(bytes, 0, bytes.Length);
                    hr.OutputStream.Close();
                }
                catch 
                {
                }

            }
        }
        /// <summary>
        /// 获取TR3返回的xml数据
        /// </summary>
        public string GetTR3()
        {
            lock (lockobj)
            {
                try
                {
                    //获取Proxy转发的TR3数据
                    Stream s = HttpContext.Current.Request.InputStream;
                    byte[] buffer = new byte[1024];//无符号 8 位整数数组
                    int count = 0;
                    StringBuilder builder = new StringBuilder();//表示可变字符字符串。

                    while ((count = s.Read(buffer, 0, 1024)) > 0)//每次读取1024个字节
                    {
                        builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
                    }
                    string sXML = builder.ToString();
                    return sXML;
                }
                catch (Exception e)
                {
                    string sStr = e.Message.ToString();
                    return sStr; //返回错误
                }
            }
        }
        #endregion

        #region 验签函数
        ///<summary>
        ///功能函数。证书验签：返回值是bool型，true表示成功，false表示失败（参数1：要验证的字符串，2：要验证的签名，3：证书文件路径，4：证书密码）
        ///<summary>
        public static bool SHA1Verify(string str_VerifySign, string signMsg, string pubkey_path, string cer_pw)
        {
            //对数据进行验签
            X509Certificate2 x509_Cer2 = new X509Certificate2(pubkey_path, cer_pw);
            RSACryptoServiceProvider rsapub = (RSACryptoServiceProvider)x509_Cer2.PublicKey.Key;
            rsapub.ImportCspBlob(rsapub.ExportCspBlob(false));
            RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsapub);
            f.SetHashAlgorithm("SHA1");
            byte[] key = Convert.FromBase64String(signMsg);
            SHA1Managed sha = new SHA1Managed();
            byte[] name = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str_VerifySign));
            if (f.VerifySignature(name, key))//验签成功
            {
                return true;
            }
            else//验签失败
            {
                return false;
            }
        }
        //功能函数。证书验签结束
        #endregion

        #region 3DES加密/解密函数
        ///<summary>
        ///功能函数。
        /// 3DES加密
        ///<summary>
        public static string Encrypt3DES(string a_strString, string a_strKey)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

            DES.Key = ASCIIEncoding.ASCII.GetBytes(a_strKey);
            DES.Mode = CipherMode.ECB;

            ICryptoTransform DESEncrypt = DES.CreateEncryptor();

            byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(a_strString);
            return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
        }
        ///<summary>
        ///功能函数。
        /// 3DES解密
        ///<summary>
        public static string Decrypt3DES(string a_strString, string a_strKey)
        {
            TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();

            DES.Key = ASCIIEncoding.ASCII.GetBytes(a_strKey);
            DES.Mode = CipherMode.ECB;
            DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            string result = "";
            ICryptoTransform DESDecrypt = DES.CreateDecryptor();
            try
            {
                byte[] Buffer = Convert.FromBase64String(a_strString);
                result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
            }
            catch
            {

            }
            return result;
        }
        #endregion
    }
}
